package com.ruoyi.auth.controller;

import javax.servlet.http.HttpServletRequest;

import com.ruoyi.auth.service.SmsService;
import com.ruoyi.system.api.domain.SysUser;
import com.ruoyi.system.api.domain.WxUser;
import com.ruoyi.system.api.model.UserDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.auth.form.LoginBody;
import com.ruoyi.auth.form.RegisterBody;
import com.ruoyi.auth.service.SysLoginService;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.utils.JwtUtils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.security.auth.AuthUtil;
import com.ruoyi.common.security.service.TokenService;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.system.api.model.LoginUser;
import com.ruoyi.auth.form.SmsLoginBody;
import com.ruoyi.auth.service.SysLoginService;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.security.service.TokenService;
import com.ruoyi.system.api.model.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;

/**
 * token 控制
 *
 * @author ruoyi
 */
@RestController
public class TokenController {
    @Autowired
    private TokenService tokenService;

    @Autowired
    private SysLoginService sysLoginService;


    // 假设你已经有Redis和短信服务依赖
    @Autowired
    private com.ruoyi.common.redis.service.RedisService redisService;

    @Autowired
    private SmsService smsService; // 你需要实现的短信发送服务

    private static final String SMS_CODE_KEY = "SMS_CODE_";


    @PostMapping("/login")
    public R<?> login(@RequestBody LoginBody form) {
        // 用户登录
        LoginUser userInfo = sysLoginService.login(form.getUsername(), form.getPassword());
        // 获取登录token
        return R.ok(tokenService.createToken(userInfo));
    }

    @DeleteMapping("/logout")
    public R<?> logout(HttpServletRequest request) {
        String token = SecurityUtils.getToken(request);
        if (StringUtils.isNotEmpty(token)) {
            String username = JwtUtils.getUserName(token);
            // 删除用户缓存记录
            AuthUtil.logoutByToken(token);
            // 记录用户退出日志
            sysLoginService.logout(username);
        }
        return R.ok();
    }

    @PostMapping("refresh")
    public R<?> refresh(HttpServletRequest request) {
        LoginUser loginUser = tokenService.getLoginUser(request);
        if (StringUtils.isNotNull(loginUser)) {
            // 刷新令牌有效期
            tokenService.refreshToken(loginUser);
            return R.ok();
        }
        return R.ok();
    }

    @PostMapping("register")
    public R<?> register(@RequestBody RegisterBody registerBody) {
        // 用户注册
        sysLoginService.register(registerBody.getUsername(), registerBody.getPassword());
        return R.ok();
    }

    /**
     * 发送短信验证码
     */
    @PostMapping("/sendCode")
    public R<?> sendCode(@RequestParam String phone) {
        if (StringUtils.isEmpty(phone)) {
            return R.fail("手机号不能为空");
        }
        // 生成6位验证码
        String code = String.valueOf((int)((Math.random() * 9 + 1) * 100000));
        // 保存到redis，5分钟有效期
        redisService.setCacheObject(SMS_CODE_KEY + phone, code, 5L, TimeUnit.MINUTES);
        // 发送验证码
        boolean sent = smsService.sendSms(phone, code);
        if (!sent) {
            return R.fail("验证码发送失败");
        }
        return R.ok("验证码发送成功");
    }

    /**
     * 短信验证码登录
     */
    @PostMapping("/smsLogin")
    public R<?> smsLogin(@RequestBody SmsLoginBody form) {
        // 校验参数
        if (StringUtils.isEmpty(form.getPhone()) || StringUtils.isEmpty(form.getCode())) {
            return R.fail("手机号和验证码不能为空");
        }
        // 校验验证码
        String cacheCode = redisService.getCacheObject(SMS_CODE_KEY + form.getPhone());
        if (!form.getCode().equals(cacheCode)) {
            return R.fail("验证码错误或已失效");
        }
        // 通过手机号查询用户并登录
        UserDto userDto = new UserDto();
        userDto.setPhone( form.getPhone());
        WxUser user = sysLoginService.getUser(userDto);


        if (user == null) {
            return R.fail("用户不存在或未注册");
        }
        // 登录成功，返回token

        LoginUser loginUser = new LoginUser();

        SysUser sysUser = new SysUser();
        sysUser.setUserId(user.getUserId());
        sysUser.setUserName(user.getUserName());
        sysUser.setIdentity(user.getIdentity()  );
        loginUser.setSysUser(sysUser);
        loginUser.setPhone( sysUser.getPhonenumber());

        return R.ok(tokenService.createToken(loginUser));
    }

}
